package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String REDIS_KEY = "HUANXIN_TOKEN_REDIS_KEY";

    public String getHuanXinToken() {
        // 尝试从redis中获取token，如果没有则向环信发送请求
        String s = redisTemplate.opsForValue().get(REDIS_KEY);
        if (StringUtils.isNotBlank(s)){
            return s;
        }

        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/token";
        Map<String, String> requestParam = new HashMap<>();
        requestParam.put("grant_type", "client_credentials");
        requestParam.put("client_id", huanXinConfig.getClientId());
        requestParam.put("client_secret", huanXinConfig.getClientSecret());

        // 请求环信接口
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestParam, String.class);
        if (responseEntity.getStatusCodeValue() != 200){
            return null;
        }
        String body = responseEntity.getBody();
        try {
            JsonNode jsonNode = MAPPER.readTree(body);
            String token = jsonNode.get("access_token").asText();
            // 设置缓存时间，让token提前一天过期
            long expires_in = jsonNode.get("expires_in").asLong() - 86400L;
            if (StringUtils.isNotBlank(token)){
                redisTemplate.opsForValue().set(REDIS_KEY,token,expires_in, TimeUnit.MILLISECONDS);
                return token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
